package com.kystar.muxplayer;

import android.content.Context;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.kystar.muxplayer.base.TLog;
import com.kystar.muxplayer.model.Preset;
import com.kystar.muxplayer.ui.VHolder;
import java.util.List;



public class PresetAdapter extends ArrayAdapter<Preset> {
    private static int[] icons = new int[]{
            R.drawable.preset_icon_1,
            R.drawable.preset_icon_2,
            R.drawable.preset_icon_3,
            R.drawable.preset_icon_4,
            R.drawable.preset_icon_5,
            R.drawable.preset_icon_6,
            R.drawable.preset_icon_7,
            R.drawable.preset_icon_8,
            R.drawable.preset_icon_9,
            R.drawable.preset_icon_10,
    };

    ListView listView = null;
    Handler handler = new Handler();

    public PresetAdapter(Context context,List<Preset> list){
        super(context,0,list);

    }

    public PresetAdapter(@NonNull ListView listView, List<Preset> list) {
        super(listView.getContext(), 0, list);
        this.listView = listView;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Preset item = getItem(position);
        VHolder vHolder;
        if (convertView==null) {
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.layout_preset_item, parent, false);
            vHolder = new VHolder(convertView);
            convertView.setTag(vHolder);
        } else {
            vHolder = (VHolder) convertView.getTag();
        }

        if (item.isSet()) {
            vHolder.setVisible(R.id.main_preset_item_img,true);
            vHolder.setImageResource(R.id.main_preset_item_img,icons[position%icons.length]);
        } else {
            vHolder.setVisible(R.id.main_preset_item_img,false);
        }
        if (TextUtils.isEmpty(item.getName())) {
            vHolder.setText(R.id.main_preset_item_text,"预设"+ item.getId());
        } else {
            vHolder.setText(R.id.main_preset_item_text,item.getName());
        }
        return convertView;
    }

    public void scrollUp() {
        handler.removeCallbacks(runScrollUp);
        handler.removeCallbacks(runScrollDown);
        handler.postDelayed(runScrollUp, 0);
    }

    public void scrollDown() {
        handler.removeCallbacks(runScrollUp);
        handler.removeCallbacks(runScrollDown);
        handler.postDelayed(runScrollDown, 0);
    }

    Runnable runScrollUp = () -> listView.smoothScrollBy(-30, 10);
    Runnable runScrollDown = () -> listView.smoothScrollBy(30, 10);
}
